package ihm;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;

import javax.swing.JPanel;

import org.janusproject.kernel.address.AgentAddress;

import sma.agents.listeners.DeleteListener;
import sma.agents.listeners.MoveListener;
import appli.utils.Config;
import sma.agents.bodies.CircleBody;

/**
 * JPanel show all agents into localEnvironment
 * 
 * @author Etienne Sainton
 * @version 0.2
 * @deprecated this panel show all agents, which is not the right way to do. You should use TelemtrePanel 
 * to represent the agents for each telemeter, and MassCenterPanel to represent the MassCenter.
 */
public class AgentsPanel extends JPanel implements MoveListener, DeleteListener {
	
	/**
	 * Agent map. Key is the agent id.
	 * For each agent, we keep up to date this body
	 */
	private Map<AgentAddress, CircleBody> listAgents = new WeakHashMap<AgentAddress, CircleBody>();

	/**
	 * Constructor.
	 * 
	 */
	public AgentsPanel() {
		//Draw windows
		this.setBackground(Color.BLACK);
		this.setBounds(0, 0, Config.PANEL_SIZE * 2, Config.PANEL_SIZE);
	}

	/**
	 * First, draw the  black background panel
	 * Then draw each agent into the map agents
	 */
	@Override
	public void paint(Graphics g) {
		//Clear the panel
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, Config.PANEL_SIZE * 2, Config.PANEL_SIZE);

		Map<AgentAddress, CircleBody> tmpListAgents;
		
		//Copy the list
		synchronized(listAgents) {
			tmpListAgents = listAgents;
		}
		
		//And we draw agents
		try {
			for (Iterator<CircleBody> i = tmpListAgents.values().iterator() ; i.hasNext() ;){
		    	CircleBody agentBody = i.next();
				g.setColor(agentBody.getColor());
				g.drawOval((int) agentBody.getPosition().x, (int) agentBody.getPosition().y, agentBody.getDiameter(), agentBody.getDiameter());
			}
		} catch (ConcurrentModificationException e) {;}
	}

	/**
	 * Notified about a agent move. Update the agent map
	 */
	@Override
	public void onMoveAgent(AgentAddress agentAddress, CircleBody body, int groupe) {
		synchronized(listAgents) {
			listAgents.put(agentAddress, body);
		}
		repaint();
	}
	
	/**
	 * Notified about a death agent. Update the agent map
	 */
	@Override
	public void onDeleteAgent(AgentAddress agentAddress, int groupe) {
		
		synchronized(listAgents) {
			listAgents.remove(agentAddress);
		}
		repaint();
	}
	
}
